package com.stage_2.module_1;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.DbUtils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class DBUtils {
    private static Connection con;
    private static String driver;
    private static String url;
    private static String username;
    private static String password;


    //创建连接池对象 (有DBCP提供的实现类)
    public static BasicDataSource dataSource = new BasicDataSource();

    //使用静态代码块进行配置
    static {
        try {
            readinfo();
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据库连接失败");
        }

    }

    //从连接池中获取连接
    public static Connection getConnection() throws Exception {
        return con;
    }

    //归还连接
    public static void close(Connection con, Statement statement, ResultSet resultSet) {
        if (con != null && statement != null) {
            try {
                statement.close();

                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //读取配置文件
    private static void readinfo() throws Exception {
        InputStream is = DbUtils.class.getClassLoader().getResourceAsStream("db.properties");
        Properties pro = new Properties();
        pro.load(is);
        driver = pro.getProperty("driver");
        url = pro.getProperty("url");
        username = pro.getProperty("username");
        password = pro.getProperty("password");
        is.close();
    }
}